import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:citiesocial/configs/configs.dart';
import 'package:citiesocial/beans/result_entity.dart';
import 'package:citiesocial/ui/comment/toast.dart';
import 'package:citiesocial/ui/comment/loading_dialog.dart';

///
///HTTP工具类。统一使用此类进行http请求
///
class Http {
  static final Http _singleton = Http._internal();
  Http._internal();
  factory Http() => _singleton;

  static const Duration _time_out = const Duration(seconds: 30);
  static const _header = const {
    'Accept': 'application/json',
    'Connection': 'keep-alive'
  };

  ///
  ///get方法
  ///
  static Future<ResultEntity> get(url, {BuildContext context}) async {
    final http = Client();
    try {
      var response = await http
          .get(
            Configs.getUrl(url),
            headers: _header,
          )
          .timeout(_time_out);
      return _convert(context, response);
    } catch (e) {
      debugPrint('get request error = $e');
      _error(context, '网络错误，请稍后重试');
    } finally {
      try {
        http.close();
      } catch (e) {
        debugPrint('error in get\'s try-catch-finally = $e');
      }
    }
    return null;
  }

  ///
  ///post方法
  ///
  static Future<ResultEntity> post(url,
      {BuildContext context, Map<String, String> body}) async {
    final http = Client();
    debugPrint('post body = $body');
    try {
      var response = await http
          .post(
            Configs.getUrl(url),
            body: body,
            headers: _header,
          )
          .timeout(_time_out);
      return _convert(context, response);
    } catch (e) {
      debugPrint('post request error = $e');
      _error(context, '网络错误，请稍后重试');
    } finally {
      try {
        http.close();
      } catch (e) {
        debugPrint('error in post\'s try-catch-finally = $e');
      }
    }
    return null;
  }

  ///
  ///处理请求
  ///
  static ResultEntity _convert(BuildContext context, Response response) {
    ResultEntity result;
    if (response != null) {
      try {
        final body = response?.body;
        debugPrint('response = $body');
        result = ResultEntity.fromJson(json.decode(body ?? '{}'));
        if ((result.error_code != '0' && result.msg != null) ||
            (result.msg != null && result.data == null)) {
          if (result.error_code == '-500') {
            Configs.saveCartCount(0);
            Configs.saveUserState(null);
          }
          _error(context, result.msg);
        }
      } catch (e) {
        debugPrint('_convert error = $e');
      }
    } else {
      debugPrint('response = null');
    }
    return result;
  }

  ///
  ///错误提示
  ///
  static _error(BuildContext context, String message) async {
    if (context == null || message == null) return;
    // final ScaffoldState result =
    //     context.ancestorStateOfType(const TypeMatcher<ScaffoldState>());
    // if (result != null) {
    //   Scaffold.of(context).removeCurrentSnackBar();
    //   Scaffold.of(context).showSnackBar(
    //     SnackBar(
    //       content: Text('$message'),
    //     ),
    //   );
    // }

    if (LoadingDialog.isShowing) {
      try {
        await LoadingDialog.dismiss(context);
      } catch (e) {
        debugPrint('get error when toast, error0 = $e');
      }
    }
    try {
      Toast.show(context, message);
    } catch (e) {
      debugPrint('get error when toast, error1 = $e');
    }
  }
}
